<template>
  <view class="complaint-progress-page">
    <image class="page-bg" src="/static/images/bg.png" mode="aspectFill" />
    <view class="gradient-bg" :style="{ top: navBarHeight + 'px' }"></view>
    <CustomNavbar title="投诉进度查询" />
    
    <view class="page-content" :style="{ paddingTop: navBarHeight + 'px', paddingBottom: '200rpx' }">
      <!-- 标签页导航 -->
      <view class="tab-nav">
        <view 
          class="tab-item" 
          :class="{ active: activeTab === 'code' }"
          @click="switchTab('code')"
        >
          投诉编码
        </view>
        <view 
          class="tab-item" 
          :class="{ active: activeTab === 'phone' }"
          @click="switchTab('phone')"
        >
          联系电话
        </view>
        <view 
          class="tab-item" 
          :class="{ active: activeTab === 'business' }"
          @click="switchTab('business')"
        >
          业务号码
        </view>
      </view>
      
      <!-- 表单内容区域 -->
      <view class="form-card">
        <!-- 投诉编码标签页 -->
        <view v-if="activeTab === 'code'" class="tab-content">
          <view class="form-item">
            <text class="form-label">投诉编码</text>
            <input 
              class="form-input" 
              type="text" 
              placeholder="请输入"
              v-model="formData.tsbm"
              maxlength="50"
            />
          </view>

          <!-- 图形验证码 -->
        <view class="form-item">
          <text class="form-label">图形验证码</text>
          <view class="form-input-wrapper">
            <input 
              class="form-input captcha-input" 
              type="text" 
              placeholder="请输入"
              v-model="formData.verifyCode"
              maxlength="6"
            />
            <view class="captcha-image-wrapper" @click="refreshCaptcha">
              <!-- <text class="captcha-text">{{ captchaText }}</text> -->
               <image :src="flowPic" class="captcha-image" style="width: 100px; height: 38px;" />
            </view>
          </view>
        </view>
          
          <view class="form-item">
            <text class="form-label">手机号</text>
            <input 
              class="form-input" 
              type="number" 
              placeholder="请输入"
              v-model="formData.lxphone"
              maxlength="11"
            />
          </view>
          
          <view class="form-item">
            <text class="form-label">短信验证码</text>
            <view class="form-input-wrapper">
              <input 
                class="form-input sms-input" 
                type="number" 
                placeholder="请输入"
                v-model="formData.verificationCode"
                maxlength="6"
              />
              <button 
                class="sms-btn" 
                :disabled="smsDisabled"
                @click="sendSmsCode(1)"
              >
                {{ smsBtnText }}
              </button>
            </view>
          </view>
        </view>
        
        <!-- 联系电话标签页 -->
        <view v-if="activeTab === 'phone'" class="tab-content">
          <view class="form-item">
            <text class="form-label">所属地区</text>
            <picker 
              mode="selector" 
              :range="regions" 
              :value="regionIndex"
              @change="onRegionChange"
            >
              <view class="form-input-wrapper picker-wrapper">
                <input 
                  class="form-input" 
                  type="text" 
                  placeholder="请选择"
                  :value="regionIndex >= 0 ? regions[regionIndex] : ''"
                  disabled
                />
                <image class="arrow-icon" src="/static/icons/icon-right.png" mode="aspectFit" />
              </view>
            </picker>
          </view>
          
          <view class="form-item">
            <text class="form-label">手机号</text>
            <input 
              class="form-input" 
              type="number" 
              placeholder="请输入"
              v-model="formData.lxphone"
              maxlength="11"
            />
          </view>
          
          <view class="form-item">
            <text class="form-label">短信验证码</text>
            <view class="form-input-wrapper">
              <input 
                class="form-input sms-input" 
                type="number" 
                placeholder="请输入"
                v-model="formData.verificationCode"
                maxlength="6"
              />
              <button 
                class="sms-btn" 
                :disabled="smsDisabled"
                @click="sendSmsCode(2)"
              >
                {{ smsBtnText }}
              </button>
            </view>
          </view>
        </view>
        
        <!-- 业务号码标签页 -->
        <view v-if="activeTab === 'business'" class="tab-content">
          <view class="form-item">
            <text class="form-label">所属地区</text>
            <picker 
              mode="selector" 
              :range="regions" 
              :value="regionIndex"
              @change="onRegionChange"
            >
              <view class="form-input-wrapper picker-wrapper">
                <input 
                  class="form-input" 
                  type="text" 
                  placeholder="请选择"
                  :value="regionIndex >= 0 ? regions[regionIndex] : ''"
                  disabled
                />
                <image class="arrow-icon" src="/static/icons/icon-right.png" mode="aspectFit" />
              </view>
            </picker>
          </view>
          
          <view class="form-item">
            <text class="form-label">业务号码</text>
            <input 
              class="form-input" 
              type="text" 
              placeholder="请输入"
              v-model="formData.phone"
              maxlength="20"
            />
          </view>


          <!-- 图形验证码 -->
        <view class="form-item">
          <text class="form-label">图形验证码</text>
          <view class="form-input-wrapper">
            <input 
              class="form-input captcha-input" 
              type="text" 
              placeholder="请输入"
              v-model="formData.verifyCode"
              maxlength="6"
            />
            <view class="captcha-image-wrapper" @click="refreshCaptcha">
              <!-- <text class="captcha-text">{{ captchaText }}</text> -->
               <image :src="flowPic" class="captcha-image" style="width: 100px; height: 38px;" />
            </view>
          </view>
        </view>
          
          <view class="form-item">
            <text class="form-label">手机号</text>
            <input 
              class="form-input" 
              type="number" 
              placeholder="请输入"
              v-model="formData.lxphone"
              maxlength="11"
            />
          </view>
          
          <view class="form-item">
            <text class="form-label">短信验证码</text>
            <view class="form-input-wrapper">
              <input 
                class="form-input sms-input" 
                type="number" 
                placeholder="请输入"
                v-model="formData.verificationCode"
                maxlength="6"
              />
              <button 
                class="sms-btn" 
                :disabled="smsDisabled"
                @click="sendSmsCode(3)"
              >
                {{ smsBtnText }}
              </button>
            </view>
          </view>
          


        </view>
      </view>
    </view>
    
    <!-- 底部查询按钮 -->
    <view class="footer-btn-container">
      <button class="query-btn" @click="handleQuery">立即查询</button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import CustomNavbar from '@/components/CustomNavbar.vue'
import { api } from '@/utils/api'

const navBarHeight = ref(80)
const activeTab = ref('code') // 'code' | 'phone' | 'business'
const regionIndex = ref(-1)
const regions = ref(['乌鲁木齐', '克拉玛依', '吐鲁番', '哈密', '昌吉', '博乐','巴州','阿克苏','克州','喀什','和田','伊犁','奎屯', '塔城', '阿勒泰','石河子'])
const regionsCode = ref(['0991', '0990', '0995', '0902', '0994', '0909','0906','0997', '0908','0998','0903','0999','0992', '0901', '0906','0993'])

const formData = ref({
  code: '', // 投诉编码
  lxphone: '', // 手机号
  verificationCode: '', // 短信验证码
  businessNumber: '' // 业务号码
})

const flowPic = ref('')

const smsDisabled = ref(false)
const smsBtnText = ref('获取验证码')
let smsCountdown = 60
let smsTimer = null

onMounted(() => {
  const windowInfo = uni.getWindowInfo()
  const statusBarHeight = windowInfo.statusBarHeight || 0
  navBarHeight.value = statusBarHeight + 44

  refreshCaptcha()
})

// 切换标签页
const switchTab = (tab) => {

  if (activeTab.value === tab) return
  activeTab.value = tab

  if(tab==='code' || tab==='business'){
    getImgCheckCode()
  }

  // 切换标签页时清空表单
  formData.value = {
    code: '',
    phone: '',
    smsCode: '',
    businessNumber: ''
  }
  regionIndex.value = -1
  // 清除短信验证码倒计时
  if (smsTimer) {
    clearInterval(smsTimer)
    smsTimer = null
  }
  smsDisabled.value = false
  smsBtnText.value = '获取验证码'
}

// 地区选择
const onRegionChange = (e) => {
  regionIndex.value = e.detail.value
}


// 刷新图形验证码
const refreshCaptcha = () => {
  getImgCheckCode()
  // TODO: 调用接口获取图形验证码
  // 这里使用随机文本作为占位符，实际应该从接口获取图片或base64
  // captchaText.value = generateCaptchaText()
  // captchaCode.value = ''
  // console.log('刷新验证码:', captchaText.value)
}

const getImgCheckCode = () =>{
  api.getImgCheckCode({
    // wxphone: wx.getStorageSync('wxphone'),
  }).then(res => {
    const data = res.data
    console.log('获取图形验证码1111:', res)
    // var url = window.URL.createObjectURL(res)
    
        var url =  'data:image/png;base64,'+uni.arrayBufferToBase64(res);
    console.log('1111111:', url)
    flowPic.value = url;

    // if (data.code === 200) {
    //   uni.showToast({
    //     title: '获取图形验证码成功',
    //     icon: 'success'
    //   })
    // } else {
    //   uni.showToast({
    //     title: data.msg || '获取图形验证码失败',
    //     icon: 'none'
    //   })
    // }
  }).catch(err => {
    console.error('获取图形验证码失败:', err)
    uni.showToast({
      title: '获取图形验证码失败，请稍后重试',
      icon: 'none'
    })
  })
}

const sendUserCheckSmsCode  = (type) =>{
  api.sendUserCheckSmsCode({
    phone: phoneNumber.value,
    objType: type,
  }).then(res => {
    // const data = res.data
    console.log('发送详单用户发送短信:', JSON.stringify(res))
    if (res.code === 200) {
      uni.showToast({
        title: '发送短信验证码成功',
        icon: 'success'
      })
    } else {
      uni.showToast({
        title: data.msg || '发送短信验证码失败',
        icon: 'none'
      })
    }
  }).catch(err => {
    console.error('发送详单用户发送短信失败:', err)
    uni.showToast({
      title: '发送短信验证码失败，请稍后重试',
      icon: 'none'
    })
  })
}

// 发送短信验证码
const sendSmsCode = (type) => {
  // 验证手机号
  if (!formData.value.phone || !formData.value.phone.trim()) {
    uni.showToast({
      title: '请输入手机号',
      icon: 'none'
    })
    return
  }
  
  // 验证手机号格式
  const phonePattern = /^1[3-9]\d{9}$/
  if (!phonePattern.test(formData.value.phone)) {
    uni.showToast({
      title: '手机号格式不正确',
      icon: 'none'
    })
    return
  }
  
  // TODO: 调用接口发送短信验证码
  console.log('发送短信验证码，手机号:', formData.value.phone)

  sendUserCheckSmsCode(type)
  
  // 开始倒计时
  smsDisabled.value = true
  smsCountdown = 60
  
  smsTimer = setInterval(() => {
    smsCountdown--
    smsBtnText.value = `${smsCountdown}秒后重试`
    
    if (smsCountdown <= 0) {
      clearInterval(smsTimer)
      smsTimer = null
      smsDisabled.value = false
      smsBtnText.value = '获取验证码'
    }
  }, 1000)
  
  // uni.showToast({
  //   title: '验证码已发送',
  //   icon: 'success'
  // })
}

// 查询
const handleQuery = () => {
  if (activeTab.value === 'code') {
    // 投诉编码查询
    if (!formData.value.tsbm || !formData.value.tsbm.trim()) {
      uni.showToast({
        title: '请输入投诉编码',
        icon: 'none'
      })
      return
    }
    
    if (!formData.value.lxphone || !formData.value.lxphone.trim()) {
      uni.showToast({
        title: '请输入手机号',
        icon: 'none'
      })
      return
    }
    
    if (!formData.value.verificationCode || !formData.value.verificationCode.trim()) {
      uni.showToast({
        title: '请输入短信验证码',
        icon: 'none'
      })
      return
    }
    
    // TODO: 调用查询接口
    console.log('投诉编码查询:', {
      code: formData.value.code,
      phone: formData.value.phone,
      smsCode: formData.value.smsCode
    })
    
  } else if (activeTab.value === 'phone') {
    // 联系电话查询
    if (regionIndex.value === -1) {
      uni.showToast({
        title: '请选择所属地区',
        icon: 'none'
      })
      return
    }
    
    if (!formData.value.lxphone || !formData.value.lxphone.trim()) {
      uni.showToast({
        title: '请输入手机号',
        icon: 'none'
      })
      return
    }
    
    if (!formData.value.verificationCode || !formData.value.verificationCode.trim()) {
      uni.showToast({
        title: '请输入短信验证码',
        icon: 'none'
      })
      return
    }
    
    // TODO: 调用查询接口
    console.log('联系电话查询:', {
      areaCode: regions.value[regionIndex.value],
      lxphone: formData.value.phone,
      verificationCode: formData.value.smsCode
    })
    
  } else if (activeTab.value === 'business') {
    // 业务号码查询
    if (regionIndex.value === -1) {
      uni.showToast({
        title: '请选择所属地区',
        icon: 'none'
      })
      return
    }
    
    if (!formData.value.phone || !formData.value.phone.trim()) {
      uni.showToast({
        title: '请输入业务号码',
        icon: 'none'
      })
      return
    }
    
    // TODO: 调用查询接口
    console.log('业务号码查询:', {
      region: regions.value[regionIndex.value],
      businessNumber: formData.value.phone
    })
  }

  console.log('查询投诉订单参数:', {
    wxphone: wx.getStorageSync('wxphone'),
    objType:2,
    ...formData.value
  })

  var objType = 1
  if(activeTab.value === 'code'){
    objType = 1
  }else if(activeTab.value === 'phone'){
    objType = 2
  }else if(activeTab.value === 'business'){
    objType = 3
  }

  api.qryWorkOrder({
    objType:objType,
    areaCodeName: regions.value[regionIndex.value],
    ...formData.value
  }).then(res => {
    console.log('查询投诉订单:', JSON.stringify(res))
    if (res.code === 200) {
       // TODO: 调用查询接口
      // 查询成功后跳转到订单列表页面
      // 这里可以根据查询参数传递数据
      const queryParams = {
        // orderId: res.data || '',
        wxxcxtype:res.data || '',
        // type: activeTab.value,
        // ...formData.value
      }
      
      uni.navigateTo({
        url: `/pages/complaint-orders/complaint-orders?queryParams=${encodeURIComponent(JSON.stringify(queryParams))}`,
        success: () => {
          console.log('跳转到投诉订单页面成功')
        },
        fail: (err) => {
          console.error('跳转失败:', err)
          uni.showToast({
            title: '跳转失败',
            icon: 'none'
          })
        }
      })
    } else {
      uni.showToast({
        title: '查询失败',
        icon: 'none'
      })
    }
  }).catch(err => {
    console.error('查询投诉订单失败:', err)
    uni.showToast({
      title: '查询失败',
      icon: 'none'
    })
  })
  
  
 
}
</script>

<style scoped>
.complaint-progress-page {
   
  position: relative;
  z-index: 1;
}

.page-bg {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: -1;
  pointer-events: none;
  object-fit: cover;
}

.gradient-bg {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1;
  pointer-events: none;
  backdrop-filter: blur(40rpx);
  background: rgba(255, 255, 255, 0.8);
}

.page-content {
  position: relative;
  z-index: 2;
  padding: 32rpx;
}

/* 标签页导航 */
.tab-nav {
  display: flex;
  /* background: rgba(255, 255, 255, 0.9);    */
  border-radius: 16rpx;
  padding: 8rpx;
  margin-bottom: 32rpx;
  gap: 8rpx;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 20rpx 0;
  font-size: 28rpx;
  color: rgba(51, 51, 51, 1);
  font-weight: 400;
  border-radius: 12rpx;
  transition: all 0.3s;
  position: relative;
}

.tab-item.active {
  color: rgba(78, 138, 254, 1);
  font-weight: 500;
  /* background: rgba(78, 138, 254, 0.1); */
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60rpx;
  height: 4rpx;
  background: rgba(78, 138, 254, 1);
  border-radius: 2rpx;
}

/* 表单卡片 */
.form-card {
  border-radius: 16rpx;
  padding: 40rpx 32rpx;
  /* background: rgba(255, 255, 255, 0.9); */
}

.tab-content {
  display: flex;
  flex-direction: column;
}

.form-item {
  margin-bottom: 40rpx;
}

.form-item:last-child {
  margin-bottom: 0;
}

.form-label {
  color: rgba(51, 51, 51, 1);
  font-family: HarmonyOS Sans SC;
  font-size: 28rpx;
  font-weight: 400;
  line-height: 32rpx;
  margin-bottom: 16rpx;
  display: block;
}

.form-input-wrapper {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.picker-wrapper {
  position: relative;
}

.form-input {
  flex: 1;
  height: 80rpx;
  padding: 0 24rpx;
  border: 2rpx solid rgba(204, 204, 204, 1);
  border-radius: 16rpx;
  font-family: HarmonyOS Sans SC;
  font-size: 28rpx;
  font-weight: 400;
  line-height: 80rpx;
  color: rgba(51, 51, 51, 1);
  background: rgba(255, 255, 255, 1);
}

.form-input::placeholder {
  color: rgba(153, 153, 153, 1);
}

.form-input[disabled] {
  background: rgba(248, 248, 248, 1);
  color: rgba(153, 153, 153, 1);
}

.sms-input {
  flex: 1;
}

.sms-btn {
  width: 180rpx;
  height: 80rpx;
  background: rgba(78, 138, 254, 1);
  color: rgba(255, 255, 255, 1);
  border-radius: 8rpx;
  font-family: HarmonyOS Sans SC;
  font-size: 28rpx;
  font-weight: 400;
  line-height: 80rpx;
  text-align: center;
  border: none;
  padding: 0;
  flex-shrink: 0;
  white-space: nowrap;
}

.sms-btn[disabled] {
  background: rgba(204, 204, 204, 1);
  color: rgba(255, 255, 255, 1);
}

.arrow-icon {
  width: 32rpx;
  height: 32rpx;
  flex-shrink: 0;
  position: absolute;
  right: 24rpx;
  top: 50%;
  transform: translateY(-50%);
  opacity: 0.6;
}

/* 底部按钮容器 */
.footer-btn-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 32rpx;
  padding-bottom: calc(32rpx + env(safe-area-inset-bottom));
  /* background: rgba(255, 255, 255, 0.95); */
  z-index: 100;
  /* box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.05); */
}

.query-btn {
  width: 100%;
  height: 88rpx;
  background: rgba(78, 138, 254, 1);
  color: rgba(255, 255, 255, 1);
  border-radius: 44rpx;
  font-family: HarmonyOS Sans SC;
  font-size: 32rpx;
  font-weight: 500;
  line-height: 88rpx;
  text-align: center;
  border: none;
  padding: 0;
}
</style>

